package com.epoint.springsecuritylearning.rbac.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.epoint.springsecuritylearning.frameuser.entity.FrameUser;
import com.epoint.springsecuritylearning.frameuser.mapper.FrameUserMapper;
import com.epoint.springsecuritylearning.rbac.entity.FrameRole;
import com.epoint.springsecuritylearning.rbac.entity.FrameRolemodulerelation;
import com.epoint.springsecuritylearning.rbac.entity.FrameUserrolerelation;
import com.epoint.springsecuritylearning.rbac.mapper.FrameModuleMapper;
import com.epoint.springsecuritylearning.rbac.mapper.FrameRoleMapper;
import com.epoint.springsecuritylearning.rbac.mapper.FrameRolemodulerelationMapper;
import com.epoint.springsecuritylearning.rbac.mapper.FrameUserrolerelationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class FrameCommonService {

    @Autowired
    private FrameUserMapper userMapper;

    @Autowired
    private FrameRoleMapper roleMapper;

    @Autowired
    private FrameUserrolerelationMapper userrolerelationMapper;

    @Autowired
    private FrameModuleMapper moduleMapper;

    @Autowired
    private FrameRolemodulerelationMapper rolemodulerelationMapper;

    public List<String> getModuleCodesByUserName(String userName){
        QueryWrapper<FrameUser> frameUserQueryWrapper = new QueryWrapper<>();
        frameUserQueryWrapper.eq("username", userName);
        FrameUser frameUser = userMapper.selectOne(frameUserQueryWrapper);

        if(frameUser == null){
            return new ArrayList<>();
        }

        // 通过userguid来查询对应的角色
        QueryWrapper<FrameUserrolerelation> frameRoleQueryWrapper = new QueryWrapper<>();
        frameRoleQueryWrapper.eq("userguid", frameUser.getRowguid());
        List<FrameUserrolerelation> frameRoles = userrolerelationMapper.selectList(frameRoleQueryWrapper);

        List<String> roleGuidList = new ArrayList<>();

        for(FrameUserrolerelation role : frameRoles){
            roleGuidList.add(role.getRoleguid());
        }

        // 通过用户所持有的角色来查询对应的模块code
        // 这里用到多表查询
        return roleGuidList.isEmpty() ? new ArrayList<>() : rolemodulerelationMapper.getModuleCodeListByRoles(roleGuidList);
    }


}
